package com.li.toolkit.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import com.li.toolkit.constant.LogConst;
import com.li.toolkit.constant.NumConst;
import com.sun.istack.internal.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author LiDong
 * @version 1.0.0
 * @createTime 3/10/2022 8:35 AM
 */
public final class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    private static final Integer TIME_OUT = 15000;

    private HttpUtils() {
    }

    /**
     * Http get请求
     *
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static String doGet(String httpUrl) {
        // 链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuilder result = new StringBuilder();
        try {
            // 创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求方式
            connection.setRequestMethod("GET");
            // 设置连接超时时间
            connection.setReadTimeout(TIME_OUT);
            // 开始连接
            connection.connect();
            // 获取响应数据
            if (connection.getResponseCode() == NumConst.TWO_HUNDRED) {
                // 获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
                    String temp;
                    while (true) {
                        String readLine = br.readLine();
                        if (null == (temp = readLine)) {
                            break;
                        }
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            logger.error(LogConst.ERROR, e);
        } finally {
            try {
                if (null != br) {
                    br.close();
                }
                if (null != is) {
                    is.close();
                }
                // 关闭远程连接
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                logger.error(LogConst.ERROR, e);
            }
        }
        return result.toString();
    }

    /**
     * Http post请求
     *
     * @param httpUrl 连接
     * @param param   参数
     * @return String
     */
    public static String doPost(String httpUrl, @Nullable String param) {
        StringBuilder result = new StringBuilder();
        // 连接
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            // 创建连接对象
            URL url = new URL(httpUrl);
            // 创建连接
            connection = (HttpURLConnection) url.openConnection();
            // 设置请求方法
            connection.setRequestMethod("POST");
            // 设置连接超时时间
            connection.setConnectTimeout(TIME_OUT);
            // 设置读取超时时间
            connection.setReadTimeout(TIME_OUT);
            // DoOutput 设置是否向 httpUrlConnection 输出，DoInput 设置是否从 httpUrlConnection 读入，此外发送 post 请求必须设置这两个
            // 设置是否可读取
            connection.setDoOutput(true);
            connection.setDoInput(true);
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            connection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //拼装参数
            if (param != null && param.isEmpty()) {
                //设置参数
                os = connection.getOutputStream();
                //拼装参数
                os.write(param.getBytes(StandardCharsets.UTF_8));
            }
            // 读取响应
            if (connection.getResponseCode() == NumConst.TWO_HUNDRED) {
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "GBK"));
                    String temp;
                    while (true) {
                        String readLine = br.readLine();
                        if (null == (temp = readLine)) {
                            break;
                        }
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }

        } catch (IOException e) {
            logger.error(LogConst.ERROR, e);
        } finally {
            //关闭连接
            try {
                if (br != null) {
                    br.close();
                }
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (Exception e) {
                logger.error(LogConst.ERROR, e);
            }
        }
        return result.toString();
    }


}
